package com.example.lenovo.boradcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    private IntentFilter mIntentFilter;
    /*
    创建一个IntentFilter实例，然后将android.net.conn.CONNECTIVITY_CHANGE
    传入到实例中，也就是说我们想要监听什么样的广播就传入什么样的数值，然后
    使用注册receiver，动态的广播接收器一定要取消注册，所以在destory要调用
    unregisterReceiver
     */

    private NetworkChangReceiver mNetworkChangeReceiver;
    /*
        NetworkChangeReceiver是继承BroadcastReceiiver
    */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        mNetworkChangeReceiver = new NetworkChangReceiver();
        registerReceiver(mNetworkChangeReceiver,mIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetworkChangeReceiver);
    }
    class NetworkChangReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectionManager = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
            if(networkInfo !=null && networkInfo.isAvailable()){
                Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
            }
            else
                Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();

        }
    }
}
